package com.dongdongshop.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.service.user.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

/**
 * @Author Eayon
 * @Date 2020/3/10 15:39
 */
public class UserRealm extends AuthorizingRealm {

    @Reference(check = false)
    private UserService userService;

    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取token
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        //调用数据库查询该账号信息
        List<TbUser> list = userService.getUserByUsername(token.getUsername());
        //如果集合为空说明该账号不存在
        if(list.size() <= 0){
            return null;
        }
        //取出该账号信息
        TbUser u = list.get(0);

        //判断密码
        //第一个参数：假如密码正确 也就是登录后的用户对象  相当于放入session
        //第二个参数：数据库查询出来的密文密码，shiro会自动帮我们校验是否正确
        //第三个参数：改用的盐，本服务中的用户盐为该用户的用户名  其他服务不一定一样
        //第四个参数：假如密码正确 就是登录后该用户的用户名
        return new SimpleAuthenticationInfo(u,u.getPassword(),ByteSource.Util.bytes(u.getUsername()),u.getUsername());
    }
}
